/*
 * SortedBuffer.cpp
 *
 *  Created on: 06/02/2014
 *      Author: Bruno
 */
#include "Tuple.h"
#include "SortedBuffer.h"
#include <stdlib.h>
#include <iostream>

using namespace std;

SortedBuffer::SortedBuffer() {

	this->buff = NULL;
	this->sizeBuff = 0;
}

bool SortedBuffer::isEmpty() {

	return this->sizeBuff == 0;
}

void SortedBuffer::push(Tuple * t) {

	Node* n = new Node();
	n->elem = t;
	n->sig = this->buff;

	if (this->sizeBuff == 0) {
		buff = n;
		n->sig = NULL;
		this->sizeBuff++;
		return;
	}

	Node* aux = NULL;
	while (n->sig != NULL && n->sig->elem->lastAct() > n->elem->lastAct()) {
		aux = n->sig;
		n->sig = n->sig->sig;
	}

	if (aux == NULL) {
		buff = n;
	} else {
		aux->sig = n;
	}
	this->sizeBuff++;
}

int SortedBuffer::size() {
	return this->sizeBuff;
}

Tuple* SortedBuffer::pop() {

	Tuple * t = this->buff->elem;
	Node * aux = this->buff;
	this->buff = this->buff->sig;
	delete aux;
	this->sizeBuff--;
	return t;
}

void SortedBuffer::clean() {

	Tuple * t = NULL;
	while(this->buff != NULL){
		t = this->pop();
		delete t;
	}
	this->buff = NULL;
	this->sizeBuff = 0;

}

void SortedBuffer::print() {

	cout<<"SortedBuffer: ";
	for(Node * aux = this->buff; aux != NULL; aux = aux->sig){

		cout<< aux->elem->lastAct() << " | ";
	}
	cout<<endl;
}


SortedBuffer::~SortedBuffer() {
	this->clean();
}

